//
//  UIViewControllerExtensionsForHUD.swift
//  Pintuan
//
//  Created by yiwanjun on 27/09/2017.
//  Copyright © 2017 jwsszle, Inc. All rights reserved.
//

import UIKit

public extension UIViewController {
    func showHUDProcess() {
        view.showHUDProcess()
    }
    func hiddenHUDProcess() {
        view.hiddenHUDProcess()
    }

    func showHUD(){
        guard let navigationView = navigationController?.view else {
            return
        }
        view.showHUD(to: navigationView)
    }

    func hiddeHUD() {
        guard let navigationView = navigationController?.view else {
            return
        }
        view.hiddeHUD(to: navigationView)
    }

    func showTip(_ content: String, action: Selector? = nil) {
        view.showTip(content, action: action)
    }
    
    func hiddeTip() {
        view.hiddeTip()
    }
    
    func delayHiddenHUD() {
        guard let navigationView = navigationController?.view else {
            return
        }
        view.delayHiddenHUD(to: navigationView)
    }
}

public extension UIView {
    func showHUDProcess(){
        if let _ = viewWithTag(9526) {
            return
        }
        let container = UIView(frame: CGRect(x: 0, y: 0, width: 72, height: 72))
        container.center = CGPoint(x: self.width/2, y: self.height/2)
        container.tag = 9526
        container.setCornerRadius(radius: 5)
        container.backgroundColor = UIColor.white
        addSubview(container)
        
        let indicator = UIActivityIndicatorView(style: .gray)
        indicator.center = CGPoint(x: container.width/2, y: container.height/2)
        indicator.startAnimating()
        container.addSubview(indicator)
        
        bringSubviewToFront(container)
    }
    
    func hiddenHUDProcess(){
        guard let containerView = viewWithTag(9526) else{
            return
        }
        containerView.removeFromSuperview()
    }
    
    func showHUD(to mainView: UIView){
        let container = UIView(frame: mainView.bounds)
        container.tag = 9527
        container.backgroundColor = UIColor.white
        mainView.addSubview(container)
        mainView.bringSubviewToFront(container)
        
        let indicator = UIActivityIndicatorView(style: .gray)
        indicator.center = CGPoint(x: container.width/2, y: container.height/2)
        indicator.startAnimating()
        container.addSubview(indicator)
    }
    
    func hiddeHUD(to mainView: UIView){
        var containerView: UIView?
        containerView = mainView.viewWithTag(9527)
        UIView.animate(withDuration: 0.3) {
            containerView?.alpha = 0.4
        } completion: { finished in
            containerView?.removeFromSuperview()
        }
    }
    
    func showTip(_ content: String, action: Selector? = nil) {
        let container = UIView(frame: bounds)
        container.tag = 9528
        container.backgroundColor = UIColor.groupTableViewBackground
        addSubview(container)
        
        if let action = action {
            container.isUserInteractionEnabled = true
            let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: action)
            container.addGestureRecognizer(tap)
        }
        
        
        let tipLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 25))
        tipLabel.center = CGPoint(x: container.width/2, y: container.height/2)
        tipLabel.font = UIFont.systemFont(ofSize: 14)
//        tipLabel.textColor = UIColor.qy.mainTitle
        tipLabel.textAlignment = .center
        tipLabel.text = content
        container.addSubview(tipLabel)
        
        bringSubviewToFront(container)
    }
   
    
    func hiddeTip(){
        var containerView: UIView?
        subviews.forEach { (view) in
            if view.tag == 9528 {
                containerView = view
                return
            }
        }
        containerView?.isHidden = true
        containerView?.removeFromSuperview()
    }

    
    func delayHiddenHUD(to mainView: UIView){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: {
            self.hiddeHUD(to: mainView)
        })
    }
}

public extension UIViewController {
    class func currentNavigationViewController() -> UINavigationController? {
        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            if rootVC is UITabBarController {
                let tabBarVC = rootVC as! UITabBarController
                
                let selectedVC = tabBarVC.selectedViewController
                if let nav = selectedVC as? UINavigationController {
                    return nav
                }
                return nil
            }
            return nil
        }
        return nil
    }
    /// 获取当前可见的视图控制器
    /// - Returns: UIViewController
     @objc class func currentViewController() -> UIViewController {
        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            if rootVC is UITabBarController {
                let tabBarVC = rootVC as! UITabBarController

                let selectedVC = tabBarVC.selectedViewController
                if selectedVC is UINavigationController {
                    let navigationVC = selectedVC as! UINavigationController
                    if let lastVC = navigationVC.viewControllers.last {
                        return UIViewController.presentingViewController(viewController: lastVC)
                    }
                }
            }
            else if rootVC is UINavigationController {
                let navigationVC = rootVC as! UINavigationController
                if let lastVC = navigationVC.viewControllers.last {
                    return UIViewController.presentingViewController(viewController: lastVC)
                }
            }
            return UIViewController.presentingViewController(viewController: rootVC)
        }
        return UIViewController()
    }

    private static func presentingViewController(viewController: UIViewController) -> UIViewController {
        if viewController is UINavigationController {
            let navigationVC = viewController as! UINavigationController
            if let lastVC = navigationVC.viewControllers.last {
                if let pVC = lastVC.presentedViewController {
                    return UIViewController.presentingViewController(viewController: pVC)
                }
                else {
                    return lastVC
                }
            }

        }
        else {
            if let pVC = viewController.presentedViewController {
                return UIViewController.presentingViewController(viewController: pVC)
            }
            else {
                return viewController
            }
        }
        return viewController

    }

    @discardableResult
    /// 直接presentViewController，自定获取 currentViewController
    /// - Parameter viewController: 需要 present 的 ViewController
    /// - Returns: 是否 present 成功
    static func presentViewController(viewController: UIViewController) -> Bool {
        let currentViewController = self.currentViewController()
        currentViewController.present(viewController, animated: true, completion: nil)
        return true
    }

    @discardableResult
    /// 直接pushViewController，自定获取 currentViewController
    /// - Parameter viewController:  需要 pushView 的 ViewController
    /// - Returns: 是否 present 成功
    static func pushViewController(viewController: UIViewController) -> Bool {
        let currentViewController = self.currentViewController()
        guard currentViewController.navigationController != nil else { return false }
        currentViewController.navigationController?.pushViewController(viewController, animated: true)
        return true
    }
}

